package gui.table;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.swing.JComboBox;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;

import api.Address;
import api.Person;
import api.Phone;

/**
 * @author Ann Raboschuk
 */
public class CustomTableModel extends AbstractTableModel
{
   private static final long serialVersionUID = 1L;
   private static String[] columNames = {"ID", "Surname", "Name", "Age", "Sex", "E-mail", "Phone", "Address"};
   private Set<TableModelListener> listeners = new HashSet<TableModelListener>();
   private List<Person> people;

   public CustomTableModel(List<Person> persons)
   {
      this.people = persons;
   }

   public void addTableModelListener(TableModelListener listener)
   {
      listeners.add(listener);
   }

   public Class<?> getColumnClass(int columnIndex)
   {
      Class<?> type = Object.class;
      switch (columnIndex)
      {
      case 0:
         type = Long.class;
         break;
      case 1:
      case 2:
      case 5:
         type = String.class;
         break;
      case 6:
      case 7:
         type = JComboBox.class;
         break;
      case 3:
         type = Integer.class;
         break;
      case 4:
         type = Character.class;
         break;
      }
      return type;
   }

   public int getColumnCount()
   {
      return 8;
   }

   public String getColumnName(int columnIndex)
   {
      return columNames[columnIndex];
   }

   public int getRowCount()
   {
      return people.size();
   }

   public Object getValueAt(int rowIndex, int columnIndex)
   {
      Person person = people.get(rowIndex);
      switch (columnIndex)
      {
      case 0:
         return person.getId();
      case 1:
         return person.getSurname();
      case 2:
         return person.getName();
      case 3:
         return person.getAge();
      case 4:
         return person.getSex();
      case 5:
         return person.getEmail();
      case 6:
         JComboBox phones = new JComboBox();
         for (Phone phone : person.getPhones())
            phones.addItem(phone.getPhone());
         return phones;
      case 7:
         JComboBox addresses = new JComboBox();
         for (Address address : person.getAddresses())
            addresses.addItem(address.toString());
         return addresses;
      }
      return "";
   }

   public boolean isCellEditable(int rowIndex, int columnIndex)
   {
      boolean isEditable = false;
      if (columnIndex == 6 || columnIndex == 7)
         isEditable = true;
      return isEditable;
   }

   public void removeTableModelListener(TableModelListener listener)
   {
      listeners.remove(listener);
   }
}
